<script setup lang="ts">
import { onMounted, onUnmounted, ref, watch } from 'vue';

import { useResizeObserver } from '@vueuse/core';
import * as echarts from 'echarts';

interface ChartData {
  books?: string[];
  values?: number[];
  organization?: string[];
}

const props = defineProps({
  chartData: {
    type: Object as () => ChartData,
    default: () => ({
      books: [],
      values: [],
      organization: [],
    }),
  },
});

const chartRef = ref<HTMLDivElement | null>(null);
let chart: echarts.ECharts | null = null;

const initChart = () => {
  if (!chartRef.value) return;
  chart = echarts.init(
    chartRef?.value.querySelector('#horizontalChart') as HTMLElement,
  );

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      top: '0%',
      left: '10%',
      right: '10%',
      bottom: '0',
      containLabel: true,
    },
    xAxis: {
      type: 'value',
      max: 400,
      axisLine: {
        show: true,
        lineStyle: {
          color: '#0077FF',
        },
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: 'rgba(0,119,255,0.2)',
        },
      },
      axisLabel: {
        color: '#fff',
      },
    },
    yAxis: {
      type: 'category',
      data: props.chartData.books,
      axisLine: {
        show: true,
        lineStyle: {
          color: '#0077FF',
        },
      },
      axisLabel: {
        color: '#fff',
        fontSize: 8,
        interval: 0,
        margin: 0,
      },
    },
    dataZoom: [
      {
        type: 'slider',
        yAxisIndex: 0,
        left: '25px',
        right: '98%',
        width: 12,
        height: '80%',
        top: '10%',
        orient: 'vertical',
        handleSize: '100%',
        textStyle: {
          color: '#fff',
        },
      },
    ],
    series: [
      {
        type: 'bar',
        data: props.chartData.values,
        barWidth: 8,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#FFE700' },
            { offset: 1, color: '#FFBA00' },
          ]),
          borderRadius: [0, 4, 4, 0],
        },
        label: {
          show: true,
          position: 'right',
          color: '#fff',
          fontSize: 12,
        },
      },
    ],
  };

  chart.setOption(option);
};

// 监听数据变化
watch(
  () => props.chartData,
  () => {
    initChart();
  },
  { deep: true },
);

// 监听容器大小变化
useResizeObserver(chartRef, () => {
  chart?.resize();
});

onMounted(() => {
  initChart();
});

onUnmounted(() => {
  chart?.dispose();
});
</script>

<template>
  <div class="chart-container" ref="chartRef">
    <div class="chart" id="horizontalChart"></div>
  </div>
</template>

<style scoped>
.chart-container {
  position: relative;
  width: 100%;
}

.chart {
  width: 100%;
  height: 220px;
  /* padding: 12px; */
}
</style>
